package com.example.util.handler;

import java.beans.PropertyDescriptor;
import java.lang.reflect.Method;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.util.ArrayList;
import java.util.List;

/**
 * @program: sms
 * @description:
 * @author: zhanghz001
 * @create: 2020-11-09 19:40
 **/
public class BeanListHandler<T> implements ResultSetHandler<T> {
    private Class<T> beanClass;

    public BeanListHandler(Class<T> beanClass) {
        this.beanClass = beanClass;
    }

    @Override
    public List<T> handler(ResultSet rs) {

        List<T> list = new ArrayList<>();
        try {
            while (rs.next()) {
                T bean = beanClass.getConstructor().newInstance();
                //源数据
                ResultSetMetaData rsmd = rs.getMetaData();
                int columnCount = rsmd.getColumnCount();
                for (int i = 1; i <= columnCount; i++) {
                    String columnName = rsmd.getColumnName(i);
                    Object columnValue = rs.getObject(columnName);

                    PropertyDescriptor pd = new PropertyDescriptor(
                            columnName.toLowerCase(), beanClass
                    );
                    Method writeMethod = pd.getWriteMethod();
                    writeMethod.invoke(bean, columnValue);

                }
                list.add(bean);
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {

        }
        return list;
    }
}
